import store from "@/store";
import axios from "axios";
import { Loading, Message, MessageBox } from "element-ui";
import { getToken } from "@/utils/index.js";
let requestData;
let loadingE;
let mode = process.env.NODE_ENV;

const service = axios.create({
  baseURL: "",
  // timeout: 30000 // 超时时间
});
export const test_token =
  "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxNDY1MTQ0MjM4MjA2NDIzMDQyIiwiaXAiOiIgIiwidXNlckFjY291bnQiOiJhZG1pbl9kZmN2IiwidGVuYW50SWQiOiIxNDY1MTQ0MjM4MTY0NDgwMDAyIiwidGVuYW50Q29kZSI6ImRmY3YiLCJleHAiOjE2NjE0OTg0NTEsInVzZXJOYW1lIjoi57O757uf566h55CG5ZGYIiwiaWF0IjoxNjYxNDEyMDUxLCJ1c2VyQ29kZSI6ImRmY3YifQ.tGVztX8055J7vjTaejc8b6weCQPweW6kkZ8OC8zDTDw";

// 请求拦截
service.interceptors.request.use(
  (request) => {
    // console.log("request", request);
    // token配置
    request.headers["Authorization"] = store.state.user.token;
    if (process.env.NODE_ENV === "serve") {
      request.headers["Authorization"] = test_token;
    }
    /* 下载文件*/
    if (request.isDownLoadFile) {
      request.responseType = "blob";
    }
    if (request.isUploadFile) {
      console.log("上传的是文件", request);
      request.headers["Content-Type"] = "multipart/form-data";
    }
    requestData = request;
    if (request.bfLoading) {
      loadingE = Loading.service({
        lock: true,
        text: "数据载入中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)",
      });
    }
    /*
     *params会拼接到url上
     * */
    if (request.isParams) {
      request.params = request.data;
      request.data = {};
    }

    //! 使用级联 Hooks 后需要在网络请求这里做拦截
    //! 此处拦截 get
    if (request.params) {
      const params = {};
      Object.keys(request.params).map((item) => {
        params[item.replace("_", "")] = request.params[item];
      });
      request.params = params;
    }

    //! 此处拦截 post
    if (request.data && !request.data instanceof FormData) {
      const data = {};
      Object.keys(request.data).map((item) => {
        data[item.replace("_", "")] = request.data[item];
      });
      request.data = data;
    }

    return request;
  },
  (err) => {
    Promise.reject(err);
  }
);
// 响应拦截
service.interceptors.response.use(
  (res) => {
    // console.log("res", res);
    if (requestData.afHLoading && loadingE) {
      loadingE.close();
    }
    // 如果是下载文件直接返回
    if (requestData.isDownLoadFile) {
      return res.data;
    }
    if (
      res.code === 401 ||
      res.data.code == 200 ||
      res.data.status ||
      res.data.code == 0 ||
      res.data.reasonCode === 200 ||
      res.data.code == 1
    ) {
      console.log(res.data);
      return res.data;
    } else {
      // 异常
      const { msg, data, message } = res;
      Message.error(
        msg || message || (data && data.msg) || (data && data.message)
      );
      return Promise.reject("error");
    }
  },
  (err) => {
    if (loadingE) {
      loadingE.close();
    }
    if (err.toString().includes("401") || err.tostring().includes(401)) {
      store.dispatch("user/resetToken");
      return window.parent.postMessage(
        {
          code: "tokenTimeOut",
          query: { id: 1, text: "测试参数" },
        },
        "*"
      );
    }
    if (err && err.response && err.response.status) {
      if (err.response.status === 403 || err.response.status === 401) {
      } else {
        Message({
          message: err,
          type: "error",
          duration: 2 * 1000,
        });
      }
    } else {
      return Message({
        message: "网络出错，请检查您的网络",
        type: "error",
        duration: 2 * 1000,
      });
    }
    return Promise.reject(err);
  }
);

const str = window.location.toString();

const isDev = str.includes("dev");

export default function khReqMethod({
  url,
  data,
  method,
  isParams,
  bfLoading,
  afHLoading,
  isUploadFile,
  isDownLoadFile,
  baseURL,
  timeout,
  headers,
  isOldApi = false,
}) {
  let config = {
    url: isOldApi ? url : process.env.VUE_APP_BASE_URL + url,
    method: method || "post",
    data: data || {},
    isParams: isParams || method != "POST" ? true : false,
    bfLoading: bfLoading || false,
    afHLoading: afHLoading || true,
    isUploadFile: isUploadFile || false,
    isDownLoadFile: isDownLoadFile || false,
    baseURL:
      isOldApi && process.env.NODE_ENV === "build"
        ? `https://dfcv-${isDev ? "dev" : "uat"}.intranet.ruixiude.com:15933/`
        : "", // 设置基本基础url
    timeout: timeout || 10000, // 配置默认超时时间
  };
  if (method && method == "get" && data) {
    const arr = [];
    Object.entries(data).forEach((item) => {
      let v = item[1];
      v =
        v !== null && v !== "" && v !== undefined
          ? encodeURIComponent(item[1])
          : "";
      arr.push(`${item[0]}=${v}`);
    });
    config.url =
      process.env.VUE_APP_BASE_URL +
      url +
      `${url.includes("?") ? "&" : "?"}${arr.join("&")}`;
    config.data = {};
  }
  if (headers) config.headers = headers;
  return service(config);
}
